package com.hydra.framework.sp;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import androidx.annotation.NonNull;

import com.hydra.framework.event.core.EventAction;
import com.hydra.framework.event.core.EventReceiver;
import com.hydra.framework.event.core.EventReceiverList;
import com.hydra.framework.event.kvo.KvoFieldAnnotation;
import com.hydra.framework.event.kvo.KvoSource;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by Hydra on 2017/8/21.
 */
public class JSetting extends KvoSource {

    public static final String kvo_version = "version";
    @KvoFieldAnnotation(name = kvo_version)
    public int version = 0;

    public static final String kvo_messageNotify = "messageNotify";
    @KvoFieldAnnotation(name = kvo_messageNotify)
    public boolean messageNotify = true;

    private SharedPreferences mSharedPreferences;

    private Map<String, Object> mValueMap;

    private int mCurrentVersion;

    public JSetting(@NonNull Context context, @NonNull String fileName, int version) {
        mCurrentVersion = version;

        mSharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);

        mValueMap = new HashMap<>();

        loadFromSp();
    }

    private void loadFromSp() {
        int version = mSharedPreferences.getInt(kvo_version, 0);

        if (mCurrentVersion != version) {
            Editor editor = mSharedPreferences.edit();

            editor.clear();
            editor.apply();
        } else {
            mValueMap.putAll(mSharedPreferences.getAll());

            for (Entry<String, Object> entry : mValueMap.entrySet()) {
                super.setValue(entry.getKey(), entry.getValue());
            }
        }
    }

    public <T> T getValue(String key, T defaultValue) {
        Object value = mValueMap.get(key);

        if (value != null) {
            return (T) value;
        }

        return defaultValue;
    }

    @Override
    public void setValue(String key, Object newValue) {


        super.setValue(key, newValue);
    }

    @Override
    protected void onAddBinding(EventAction eventAction, EventReceiver receiver, EventReceiverList receiverList) {
        super.onAddBinding(eventAction, receiver, receiverList);
    }
}
